package com.wgt.upload.util;

import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * @author wgt
 * @date 2018/1/10
 * @project fastdfs-server
 */
public class Base64Util {

    public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";


    public static String getTempFileName(String rootPath, String fileType){
        StringBuilder sb_str = new StringBuilder(rootPath);
        sb_str.append(System.currentTimeMillis()+"");
        sb_str.append(generateString(8));
        sb_str.append(fileType);
        return sb_str.toString();
    }


    public static boolean generateImage(String base64Code, String savePath)throws Exception{
        if(base64Code.isEmpty()){
            return false;
        }

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b =decoder.decodeBuffer(base64Code);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            File file = new File(savePath);
            OutputStream out = new FileOutputStream(file);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }catch (IOException e){
            throw new Exception(e);
        }
    }

    /**
     * 获取随机字符串
     * @param length
     * @return
     */
    public static String generateString(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(allChar.charAt(random.nextInt(allChar.length())));
        }
        return sb.toString();
    }
}
